﻿using MikuMikuLibrary.Databases;
using MikuMikuLibrary.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DatabaseConverter
{
    class AetMerge
    {
        public AetDatabase db = new AetDatabase();
        public AetDatabase db2 = new AetDatabase();
        public List<int> ids = new List<int>();
        public string logs = "";
        public void MergeAet(SprMerge spr)
        {
            int MaxId = 0;
            foreach (var i in db.AetSets)
            {
                if (i.Id > MaxId)
                {
                    MaxId = i.Id;
                }
                foreach (var u in i.Aets)
                {
                    ids.Add(u.Id);
                }
            }
            foreach (var i in db2.AetSets)
            {
                var stringcheck = db.AetSets.Where(c => c.Name == i.Name).FirstOrDefault();
                if (stringcheck == null)
                {
                    var findSpr = spr.db2.SpriteSets.Where(c => c.Id == i.SpriteSetId).First();
                    var findSpr2 = spr.db.SpriteSets.Where(c => c.Name == findSpr.Name).First();
                    i.SpriteSetId = (ushort)findSpr2.Id;

                    foreach (var u in i.Aets)
                    {
                        var result2 = ids.Where(c => c == u.Id).FirstOrDefault();
                        if (result2 == u.Id)
                        {
                            var maxids = ids.Max() + 1;
                            while (result2 == u.Id)
                            {
                                result2 = ids.Where(c => c == maxids).FirstOrDefault();
                                if (result2 == u.Id) maxids++;
                            }
                            u.Id = (ushort)maxids;
                        }
                        ids.Add(u.Id);
                    }

                    var result = db.AetSets.Where(c => c.Id == i.Id).FirstOrDefault();
                    if (result == null)
                    {
                        db.AetSets.Add(i);
                    }
                    else
                    {
                        result = db.AetSets.Where(c => c.Id == (ushort)(MaxId + 1)).FirstOrDefault();
                        while (result != null)
                        {
                            MaxId++;
                            result = db.AetSets.Where(c => c.Id == (ushort)(MaxId + 1)).FirstOrDefault();
                        }
                        i.Id = (ushort)(MaxId + 1);
                        db.AetSets.Add(i);
                    }
                } else
                {
                    logs = logs + ("Warning : Skipped File " + i.FileName) + "\n";
                }
            }
        }
    }
}
